﻿using System;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using System.Collections.Specialized;
using System.Windows;

namespace XmlStudio.Exceptions.Handlers {
    /// <summary>
    /// Exception policy handler for user interface.
    /// </summary>
    [ConfigurationElementType(typeof(CustomHandlerData))]
    public class UIPolicyHandler : IExceptionHandler {
        /// <summary>
        /// Initializes a new instance of the <see cref="UIPolicyHandler"/> class.
        /// </summary>
        /// <param name="ignore"></param>
        public UIPolicyHandler(NameValueCollection ignore) {
        }

        /// <summary>
        /// Handles the exception.
        /// </summary>
        /// <param name="exception"><see cref="Exception"/> to handle.</param>
        /// <param name="correlationID">???</param>
        /// <returns>Handled <see cref="Exception"/>.</returns>
        public Exception HandleException(Exception exception, Guid correlationID) {
            MessageBoxResult result = this.ShowThreadExceptionDialog(exception);
            //Exits the program when the user clicks Abort
            if(result == MessageBoxResult.Cancel) {
                System.Windows.Application.Current.Shutdown();
            }

            return exception;
        }

        private MessageBoxResult ShowThreadExceptionDialog(Exception e) {
            string errorMsg = e.Message;
            return MessageBox.Show(errorMsg, "Application Error", MessageBoxButton.OK, MessageBoxImage.Warning);
        }
    }
}
